package com.gooluke.gateway.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Component
public class JwtUtils {

    @Value("${jwt.secret:XOVE80iQzsfst8hVcJYuQ58kbPJGy9n3nKu1paAEe6w=}")
    private String secret;

    @Value("${jwt.access-token-expiration:900}")
    private long accessTokenExpiration;

    private SecretKey getSigningKey() {
        byte[] keyBytes = Decoders.BASE64.decode(secret); // 解码为字节数组
        return Keys.hmacShaKeyFor(keyBytes);
    }

    // 生成 Token
    public String generateToken(String username, List<String> roles) {
        return Jwts.builder()
                .subject(username)
                .claim("roles", roles)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + accessTokenExpiration * 1000))
                .signWith(getSigningKey()) // 使用新的签名算法常量
                .compact();
    }

    // 验证 Token（修复过时方法）
    public boolean validateToken(String token) {
        try {
            Jws<Claims> claimsJws = Jwts.parser().verifyWith(getSigningKey()).build().parseSignedClaims(token);
            Claims claims = claimsJws.getPayload();
            return claims != null && claims.getExpiration().after(new Date());
        } catch (Exception e) {
            // todo 异常处理
            return false;
        }
    }

    // 获取用户名（修复过时方法）
    public String getUsernameFromToken(String token) {
        return Jwts.parser()
                .verifyWith(getSigningKey())
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .getSubject();
    }

    // 获取角色（修复过时方法）
    @SuppressWarnings("unchecked")
    public List<String> getRolesFromToken(String token) {
        return Jwts.parser()
                .verifyWith(getSigningKey())
                .build()
                .parseSignedClaims(token)
                .getPayload()
                .get("roles", List.class);
    }

    /**
     * 生成密钥
     */
    public String generateSecret() {
        // 生成安全的 256 位（32 字节）HMAC-SHA 密钥
        SecretKey key = Jwts.SIG.HS256.key().build();
        return Base64.getEncoder().encodeToString(key.getEncoded());
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        JwtUtils jwtUtils = new JwtUtils();
        jwtUtils.secret = "XOVE80iQzsfst8hVcJYuQ58kbPJGy9n3nKu1paAEe6w=";
        jwtUtils.accessTokenExpiration = 900;
//        jwtUtils.secret = jwtUtils.generateSecret();
        String token = jwtUtils.generateToken("huang", List.of("Admin"));
        System.out.println("token = " + token);
        String userId = jwtUtils.getUsernameFromToken(token);
        System.out.println("userId = " + userId);
        List<String> roles = jwtUtils.getRolesFromToken(token);
        System.out.println("roles = " + roles);
        boolean result = jwtUtils.validateToken(token);
        System.out.println("result = " + result);
    }
}